// 题目链接：https://leetcode.com/problems/plus-one/

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function (digits) {
  for (let index = digits.length - 1; index >= 0; index--) {
    ++digits[index]

    if (digits[index] === 10) {
      digits[index] = 0
    } else {
      return digits
    }
  }
  digits.unshift(1)

  return digits
}

var plusOne1 = function (digits) {
  let flag = 1

  for (let index = digits.length - 1; index >= 0; index--) {
    digits[index] = digits[index] + flag
    digits[index] = (digits[index] >= 10) ? (flag = 1, digits[index] = 0) : (flag = 0, digits[index])
  }

  if (flag === 1) {
    digits.unshift(1)
  }

  return digits
}

var plusOne2 = function (digits) {
  const digitsCopy = digits.slice().reverse()
  const len = digitsCopy.length

  for (let index = 0; index < len - 1; index++) {
    if (digitsCopy[index] === 9) {
      const nextValue = digitsCopy[index + 1]
      digitsCopy[index] = 0
      digitsCopy[index + 1] = nextValue || 1

      if (!nextValue) break
      continue
    }
    ++digitsCopy[index]
    break
  }

  return digitsCopy.reverse()
}

const arr = [4, 3, 2, 1]

console.log(plusOne2(arr))

module.exports = {
  plusOne,
  plusOne1
}
